import axios, { type AxiosResponse } from 'axios'
import cookie from "js-cookie";
import router from '@/router';
import qs from 'qs';
import { ElMessage } from 'element-plus/lib/components/index.js';
import { useUserInfo } from '../stores/admin/index'
import nprogress from 'nprogress' // 进度条
import 'nprogress/nprogress.css' //样式必须引入

// 扩展
declare interface TyepResponse extends AxiosResponse {
    error: number,
    errmsg: string,
    errno: number,
}


let baseURL = ""
let host = ""

// console.log(process.env.NODE_ENV); // 打印结果为 'development' 

if (process.env.NODE_ENV == 'development') {
    baseURL = '/m.api';
    host = ""
} else {
    baseURL = "http://zxwyit.cn:8080/m.api"
    host = "http://zxwyit.cn:8080"
}

const instance = axios.create({
    baseURL,
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
})

instance.interceptors.request.use(function (config) {
    config.headers['AdminToken'] = cookie.get('token')
    nprogress.start()
    return config;
}, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
});
const METHOD_TYPE = ["_mt=edit", "_mt=create", "_mt=delete"]
// 添加响应拦截器
instance.interceptors.response.use(async (response) => {
    // 2xx 范围内的状态码都会触发该函数。
    // 对响应数据做点什么
    // console.log(response,"响应拦截器")
    const res = response.data
    let { errno, errmsg } = res
    let path = router.currentRoute.value.fullPath
    if (10006 === errno) {
        // ElMessage.error(errmsg)
        // router.replace({ path: "/login", query: { back: path } })
        const configData = response.config.data || "";
        var index = METHOD_TYPE.findIndex(item => configData.includes(item))
        if (-1 === index) {
            router.replace({ path: "/login", query: { back: path } })
            return
        } else {
            const store = useUserInfo()
            const { username, password } = store.loginInfo
            let loginData = { _gp: "admin", _mt: "login", username, password }
            const { errno, errmsg, data } = await post(loginData)
            if (200 == errno) {
                cookie.set("token", data)
            } else {
                router.replace({ path: "/login", query: { back: path } })
                return Promise.reject({ errno, errmsg, data })
            }
        }
        return
    }
    nprogress.done()
    return res;
}, function (error) {
    return Promise.reject(error);
});

function get(params?: object): Promise<TyepResponse> {
    return instance.get('', { params })
}
function post(data: object, params?: object): Promise<TyepResponse> {
    return instance.post('', qs.stringify(data), { params })
}
function upload(data: FormData): Promise<TyepResponse> {
    return instance.post("../upload/admin", data);//..表示上一级目录
}
const uploadPath = host + "/upload/admin"
export {
    post, get, uploadPath, upload
}